<template>
  <el-row justify="end">
    <el-col :span="16" style="text-align: left;">
      <el-button @click="addUser" type="primary">添加用户</el-button>
    </el-col>
    <el-col :span="6">
      <el-input v-model="searchInput" placeholder="请输入内容"></el-input>
    </el-col>
    <el-col :span="2">
      <el-button type="primary" @click="searchData">搜索</el-button>
    </el-col>
  </el-row>
  <el-table
    :data="
      tableData.filter(
        (data) =>
          !search || data.name.toLowerCase().includes(search.toLowerCase())
      )
    "
    :header-cell-style="{background:'#f4f3f9',color:'#606266', fontSize: '12px'}"
    :cell-style = "{fontSize: '12px'}"
    style="width: 100%; margin-top: 10px;"
  >
    <!--
    <el-table-column
      prop="id"
      label="序号"
      width="50">
    </el-table-column>
    -->
    <el-table-column prop="id" v-if="false"> </el-table-column>
    <el-table-column label="姓名" prop="realName"> </el-table-column>
    <el-table-column label="用户名" prop="userName"> </el-table-column>
    <el-table-column label="部门" prop="organizationName"> </el-table-column>
    <el-table-column label="角色" prop="roleType"> </el-table-column>
    <el-table-column label="操作" align="right">
      <template #default="scope">
          <el-button @click="delUser(scope.row)" size="small" type="danger">删除</el-button>
          <el-button @click="editUser(scope.row)" size="small" type="primary">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    small="true"
    background
    layout="prev, pager, next"
    :page-size="5"
    :total="total"
    :current-page="currentPage"
    @current-change="changePage"
    style="margin-top: 30px;">
  </el-pagination>
  <el-drawer
  title="编辑"
  v-model="drawer"
  v-show="drawer"
  :lock-scroll="false"
  :with-header="true">
      <el-form :label-position="labelPosition" label-width="80px" :model="formLabelAlign" ref="ruleFormRef" :rules="rules">
        <el-form-item label="id" v-show="false">
          <el-input v-model="formLabelAlign.id"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="formLabelAlign.realName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="formLabelAlign.userName" placeholder="请输入正确手机号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="formLabelAlign.pwd" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmpwd">
          <el-input v-model="formLabelAlign.confirmpwd" type="password" placeholder="请确认密码"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <el-tree-select
            placeholder="请选择部门"
            v-model="formLabelAlign.departmentId"
            :data="departmentList"
            style="width: 100%;"
            check-strictly
            :render-after-expand="true"
            show-checkbox
            check-on-click-node
            @check="handleNodeClick"
          />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="formLabelAlign.roleId" placeholder="请选择角色" style="width: 100%;">
              <el-option
                  v-for="role in roles"
                  :key="role.roleId"
                  :label="role.roleType"
                  :value="role.roleId"
              ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" v-if="ifEdit">保存</el-button>
          <el-button type="primary" @click="onAdd"  v-if="!ifEdit">添加</el-button>
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
  </el-drawer>
</template>
<script>
import { getManagerList, addManager, updateManager,  deleteManager } from "../api/manager.js"
import { getDepartment } from "../api/department.js"
import { getRoles } from "../api/role.js"
export default {
  data() {
    let checkPhone = (rule, value, callback) => {
        let phoneReg = /^1[3456789]\d{9}$/;
        if(phoneReg.test(value)) {
          callback();
        }
        else {
          return callback(new Error('请输入正确手机号'));
        }
    }
    let checkPwd = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          let pwdReg = /^(?=.*[a-zA-Z])(?=.*\d).{6,10}$/;
          if (pwdReg.test(value)) {
            callback();
          }
          else {
            callback(new Error('请输入包含数字、字母，且长度6位以上密码'));
          }
        }
    }
    let confirmPwd = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.formLabelAlign.pwd) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
    };
    return {
      tableData: [
      ],
      search: "",
      drawer: false,
      labelPosition: 'left',
      formLabelAlign: {
      },
      queryParams: {
        page: 1,
        size: 5
      },
      total: '',
      currentPage: 1,
      searchInput: '',
      departmentList: [],
      roles: [],
      rules: {
          realName: [
            { required: true, message: '请输姓名', trigger: 'blur' },
            { min: 2, max: 4, message: '长度在 2 到 4 个字符', trigger: 'blur' }
          ],
          userName: [
            { validator: checkPhone, required: true, trigger: 'blur' }
          ],

          pwd: [
            { validator: checkPwd, trigger: 'blur' }
          ],
          confirmpwd: [
            { validator: confirmPwd,  trigger: 'change' }
          ],
          departmentId: [
            { required: true, message: '请选择部门', trigger: 'change' }
          ],
          roleId: [
            { required: true, message: '请填写角色', trigger: 'change' }
          ]
      },
      ifEdit: false
    };
  },
  methods: {
    /**选择部门 */
    handleNodeClick(nodeobj) {
      this.formLabelAlign.organizationId = nodeobj.value;
    },
    async onAdd() {
      this.ifEdit = false;
      this.$refs['ruleFormRef'].validate(async (valid) => {
        if(valid) {
          let result = await addManager(this.formLabelAlign);
          if(result.data.status == "invalid") {
            this.$message({
              type: 'info',
              message: `该手机号已注册！`
            });
          }
          else if(result.data.status == "ok") {
            this.$message({
              type: 'success',
              message: `添加成功！`
            });
            this.formLabelAlign = {};
          }
        }
        else {
          console.log("validate error")
        }
      })
    },
    async onSubmit() {
      this.ifEdit = false;
      this.$refs['ruleFormRef'].validate(async (valid) => {
        if(valid) {
          let result = await updateManager(this.formLabelAlign);
          if(result.data.status == "invalid") {
            this.$message({
              type: 'info',
              message: `该手机号已注册！`
            });
          }
          else if(result.data.status == "ok") {
            this.$message({
              type: 'success',
              message: `保存成功！`
            });
            this.formLabelAlign = {};
          }
        }
        else {
          console.log("validate error")
        }
      })
    },
    async getManagerList() {
      this.queryParams.user = localStorage.getItem("user");
      let result = await getManagerList(this.queryParams);
      console.log(result);
      if(result.data.status == 'ok') {
        this.tableData = result.data.userList;
        this.total = result.data.total
      }
    },
    updateDept(departments) {
      for(let j = 0; j < departments.length; j++) {
        departments[j].label = departments[j].organizationName;
        departments[j].value = departments[j].organizationId;
        for(let i in departments[j]) {
          if(i == "children") {
            this.updateDept(departments[j].children);
          }
        }
      }
    },
    async getDepartment() {
      this.queryParams.user = localStorage.getItem("user");
      let result = await getDepartment(this.queryParams);
      if(result.data.status == 'ok') {
        let departments = result.data.departments;
        this.updateDept(departments);
        this.departmentList = departments;
      };

    },
    addUser() {

    },
    delUser(row) {
      
    },  
    addUser() {
      this.drawer = true;
    },
    editUser(row) {
      this.ifEdit = true;
      console.log(row);
      this.formLabelAlign.userId = row.userId;
      this.formLabelAlign.userName = row.userName;
      this.formLabelAlign.realName = row.realName;
      this.drawer = true
    },
    changePage(e) {
      this.currentPage = e;
      this.queryParams.page = e;
      this.getManagerList();
    },
    async searchData() {
      console.log(this.searchInput);
      let result = await search({'search': this.searchInput});
      if(result.data.status == 'ok') {
        this.tableData = result.data.userList;
      }
    },
    async exportData() {
      let userName = localStorage.getItem("user");
      let result = await exportFile(userName);
      console.log(result);
    },
    async getRoleList() {
      let result = await getRoles();
      this.roles = result.data.result;
    }
  },
  mounted() {
    this.getManagerList();
    this.getDepartment();
    this.getRoleList();
  }
};
</script>
<style scoped>
</style>